package com.team.childapp.ui

import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.hardware.Camera
import android.media.AudioAttributes
import android.media.ExifInterface
import android.media.SoundPool
import android.net.Uri
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.view.KeyEvent
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.children
import androidx.core.view.get
import com.huanguo.dashboard.base.activity.BaseVMActivity
import com.huanguo.dashboard.base.adapter.KotlinDataAdapter
import com.huanguo.dashboard.viewmodel.MainViewModel
import com.mig35.carousellayoutmanager.CarouselLayoutManager
import com.mig35.carousellayoutmanager.CarouselLayoutManager.HORIZONTAL
import com.mig35.carousellayoutmanager.CarouselZoomPostLayoutListener
import com.mig35.carousellayoutmanager.CenterScrollListener
import com.mig35.carousellayoutmanager.DefaultChildSelectionListener
import com.team.childapp.R
import com.team.childapp.base.App
import com.team.childapp.bean.MainItem
import com.team.childapp.config.BaseConfig
import com.team.childapp.databinding.ActivityMainBinding
import com.team.childapp.listener.CustomerCenterScrollListener
import com.team.childapp.ui.ai.AiGenerateTextByImageActivity
import com.team.childapp.ui.ai.AiMessageActivity
import com.team.childapp.ui.contacts.ContactsActivity
import com.team.childapp.ui.my.MyActivity
import com.team.childapp.ui.setting.SettingActivity
import com.team.childapp.ui.setting.SettingInformationActivity
import com.team.childapp.ui.studygarden.StudyGardenActivity
import com.team.childapp.util.LogUtils
import java.io.IOException


/**
 * 作者：suichengju
 * 时间：2024/12/17:18:10
 * 邮箱：325927775@qq.com
 * 说明：总入口
 */
class MainActivity :  BaseVMActivity<ActivityMainBinding, MainViewModel>(R.layout.activity_main) {
    private val list = arrayListOf<MainItem>()
    private var selectedContact: MainItem? = null
    private val requestCameraPermission = 10086
    private var currentSelectedIndex = 0
    private var isPlaying = false
    private var centerScrollListener: CenterScrollListener? = null
    private var soundPool: SoundPool? = null
    private var soundId: Int = 0
    private var firstTime = true
    private  var sexFlag=0;
    private val REQUEST_CODE_CAMERA = 1001
    override fun initVMData() {
//        setBarTitle("首页")

    }

    override fun initView() {


        if (sexFlag==0) {
            list.add(MainItem("相机", R.mipmap.icon_home_camera, R.raw.ai_camera_0))
            list.add(MainItem("电话", R.mipmap.icon_home_phone, R.raw.ai_phone_0))
            list.add(MainItem("相册", R.mipmap.icon_home_photo, R.raw.ai_photo_0))
            list.add(MainItem("手电筒", R.mipmap.icon_home_picture_book, R.raw.flashlight_0))
            list.add(MainItem("AI童伴", R.mipmap.icon_home_child, R.raw.ai_child_0))
            list.add(MainItem("识别", R.mipmap.icon_home_parse, R.raw.ai_input_0))
            list.add(MainItem("学习", R.mipmap.icon_home_study, R.raw.ai_study_0))
            list.add(MainItem("我的", R.mipmap.icon_home_mine, R.raw.ai_mine_0))
            list.add(MainItem("设置", R.mipmap.icon_home_setting, R.raw.ai_setting_0))
        }else if(sexFlag==1){
            list.add(MainItem("相机", R.mipmap.icon_home_camera, R.raw.ai_camera_1))
            list.add(MainItem("电话", R.mipmap.icon_home_phone, R.raw.ai_phone_1))
            list.add(MainItem("相册", R.mipmap.icon_home_photo, R.raw.ai_photo_1))
            list.add(MainItem("手电筒", R.mipmap.icon_home_picture_book, R.raw.flashlight_1))
            list.add(MainItem("AI童伴", R.mipmap.icon_home_child, R.raw.ai_child_1))
            list.add(MainItem("识别", R.mipmap.icon_home_parse, R.raw.ai_input_1))
            list.add(MainItem("学习", R.mipmap.icon_home_study, R.raw.ai_study_1))
            list.add(MainItem("我的", R.mipmap.icon_home_mine, R.raw.ai_mine_1))
            list.add(MainItem("设置", R.mipmap.icon_home_setting, R.raw.ai_setting_1))
        }
        currentSelectedIndex=App.application().getShareData().getInt(BaseConfig.HOME_SELECT_INDEX)
        if(currentSelectedIndex!=0) {
            setImageSelected(currentSelectedIndex, true)
        }
        sexFlag= App.application().getShareData().getInt(BaseConfig.USER_SEX)
        // 初始化 SoundPool
        val audioAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()

        soundPool = SoundPool.Builder()
            .setMaxStreams(5)
            .setAudioAttributes(audioAttributes)
            .build()

        // 配置 CarouselLayoutManager
        val layoutManager = CarouselLayoutManager(HORIZONTAL, true).apply {
            maxVisibleItems = 3
            setPostLayoutListener(CarouselZoomPostLayoutListener())
            addOnItemSelectionListener { adapterPosition: Int ->
                mBinding.tvTitle.text = list[adapterPosition].itemTitle
                selectedContact = list[adapterPosition]
            }
        }


        //点击事件
        DefaultChildSelectionListener.initCenterItemListener({ recyclerView, carouselLayoutManager, v ->
            val position = recyclerView.getChildLayoutPosition(v)
            App.application().getShareData().putInt(BaseConfig.HOME_SELECT_INDEX,position)
            when(position){
                0 -> {
                    checkAndRequestCameraPermission()
                }
                1 -> {
                    start<ContactsActivity>()
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
                2 -> {
//                    val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
//                    if (galleryIntent.resolveActivity(packageManager) != null) {
//                        startActivity(galleryIntent)
//                    }
                    val intent = Intent(Intent.ACTION_VIEW, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                    if (intent.resolveActivity(packageManager) != null) {
                        startActivity(intent)
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    } else {
                        // 没有找到可以处理该Intent的Activity时的处理逻辑
                        Toast.makeText(this, "没有找到相册应用", Toast.LENGTH_SHORT).show()
                    }
                }
                4 ->{
                    start<AiMessageActivity>()
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
                5 ->{
                    start<AiGenerateTextByImageActivity>()
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
                6 ->{
                    start<StudyGardenActivity>()
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
                7 -> {
                    val intent = Intent(this, SettingInformationActivity::class.java)
                    startActivity(intent)
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
                8 -> {
                    val intent = Intent(this, SettingActivity::class.java)
                    startActivity(intent)
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                }
            }
        }, mBinding.mainRecyclerView, layoutManager)
        mBinding.mainRecyclerView.isFocusableInTouchMode=false
        mBinding.mainRecyclerView.isFocusable=false
        mBinding.mainRecyclerView.apply {
            this.layoutManager = layoutManager
            setHasFixedSize(true)
            addOnScrollListener(CustomerCenterScrollListener(this@MainActivity,list))
            adapter = KotlinDataAdapter.Builder<MainItem>()
                .setLayoutId(R.layout.adapter_home_item)
                .setData(list)
                .addBindView { itemView, itemData , position->
                    itemView.findViewById<ImageView>(R.id.home_icon).setImageResource(itemData.itemIcon)
                    itemView.isFocusableInTouchMode=false
                    itemView.isFocusable = false
                    itemView.background = null
                }
                .create()
        }
    }

    //检查拨打摄像权限
    private fun checkAndRequestCameraPermission() {
        if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA), requestCameraPermission)
        } else{
            jumpToCameraActivity()
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
        }
    }

    //检查拨打摄像权限
    private fun checkAndRequestPhotoPermission() {
        if (ContextCompat.checkSelfPermission(this,android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.CAMERA), requestCameraPermission)
        } else{
            jumpToCameraActivity()
        }
    }

    private fun jumpToCameraActivity() {
        val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 设置相机方向为横向（90度）
        takePictureIntent.putExtra("android.intent.extras.CAMERA_FACING", Camera.CameraInfo.CAMERA_FACING_BACK)
        takePictureIntent.putExtra("android.intent.extras.ORIENTATION", 270)
        if (takePictureIntent.resolveActivity(packageManager) != null) {
            startActivity(takePictureIntent)
        }
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        requestedOrientation =ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        if (requestCode == REQUEST_CODE_CAMERA && resultCode == RESULT_OK) {
            val photoUri = data?.data
            if (photoUri != null) {
                try {
                    // 读取 Exif 信息
                    val exif = ExifInterface(contentResolver.openInputStream(photoUri)!!)
                    val orientation = exif.getAttributeInt(
                        ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_NORMAL
                    )

                    // 根据 Exif 信息旋转照片
                    val bitmap = rotateBitmapBasedOnExif(photoUri, orientation)
                    // 使用旋转后的 bitmap
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    private fun rotateBitmapBasedOnExif(uri: Uri, orientation: Int): Bitmap? {
        return try {
            val inputStream = contentResolver.openInputStream(uri)
            val bitmap = BitmapFactory.decodeStream(inputStream)
            inputStream?.close()

            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap, 90)
                ExifInterface.ORIENTATION_ROTATE_180 -> rotateBitmap(bitmap, 180)
                ExifInterface.ORIENTATION_ROTATE_270 -> rotateBitmap(bitmap, 270)
                else -> bitmap
            }
        } catch (e: IOException) {
            e.printStackTrace()
            null
        }
    }

    private fun rotateBitmap(bitmap: Bitmap, degrees: Int): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(degrees.toFloat())
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == requestCameraPermission) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                jumpToCameraActivity()
            } else {
                Toast.makeText(this, "无法跳转到摄像界面，权限被拒绝", Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 重写 onKeyDown 方法
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
//        setImageSelected(currentSelectedIndex, false)
        return when (keyCode) {
            KeyEvent.KEYCODE_F1 -> {

                start<AiMessageActivity>()
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                true // 表示事件已处理
            }
            KeyEvent.KEYCODE_DPAD_UP -> {
                LogUtils.showLog("当前的按键为KEYCODE_DPAD_UP，Index的值为 ：$currentSelectedIndex")

                if (currentSelectedIndex<1) {
                    currentSelectedIndex = 8
                } else {
                    currentSelectedIndex = currentSelectedIndex -1
                }
                setImageSelected(currentSelectedIndex, true)
                true // 表示事件已处理
            }
            KeyEvent.KEYCODE_DPAD_DOWN -> {
                LogUtils.showLog("当前的按键为KEYCODE_DPAD_DOWN，Index的值为 ：$currentSelectedIndex")

                if (currentSelectedIndex>7) {
                    currentSelectedIndex = 0
                } else {
                    currentSelectedIndex = currentSelectedIndex + 1
                }

                setImageSelected(currentSelectedIndex, true)
                true // 表示事件已处理
            }
            KeyEvent.KEYCODE_ENTER -> {
                when(currentSelectedIndex) {
                    0 -> {
                        checkAndRequestCameraPermission()
                    }

                    1 -> {
                        start<ContactsActivity>()
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    }

                    2 -> {
//                    val galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
//                    if (galleryIntent.resolveActivity(packageManager) != null) {
//                        startActivity(galleryIntent)
//                    }
                        val intent =
                            Intent(Intent.ACTION_VIEW, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                        if (intent.resolveActivity(packageManager) != null) {
                            startActivity(intent)
                            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                        } else {
                            // 没有找到可以处理该Intent的Activity时的处理逻辑
                            Toast.makeText(this, "没有找到相册应用", Toast.LENGTH_SHORT).show()
                        }
                    }

                    4 -> {
                        start<AiMessageActivity>()
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    }

                    5 -> {
                        start<AiGenerateTextByImageActivity>()
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    }

                    6 -> {
                        start<StudyGardenActivity>()
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    }

                    7 -> {
                        val intent = Intent(this, SettingInformationActivity::class.java)
                        startActivity(intent)
                        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                    }

                    8 -> {
                        val intent = Intent(this, SettingActivity::class.java)
                        startActivity(intent)
                        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                    }
                }
                true
            }



            else -> super.onKeyDown(keyCode, event) // 其他按键交给系统处理

        }


    }

    private fun setImageSelected(index: Int, selectEnale: Boolean) {
        mBinding.tvTitle.text = list[index].itemTitle
        selectedContact = list[index]
//        mBinding.mainRecyclerView.isFocusableInTouchMode=true

        if (index < 9) {
            mBinding.mainRecyclerView.smoothScrollToPosition(index)
            // 禁用 RecyclerView 子项的焦点
            mBinding.mainRecyclerView.isFocusableInTouchMode = false
            mBinding.mainRecyclerView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
//            mBinding.mainRecyclerView.children.get(index).isFocusableInTouchMode=false
        }
//        if (!firstTime && selectEnale) {
//            playAudio(index)
//        }
//        firstTime=false;
    }

    private fun playAudio(index: Int) {
        // 加载音频文件，这里假设音频文件在res/raw目录下，名为audio_file.mp3
        soundId = soundPool?.load(this, list.get(index).itemAudio, 1) ?:
        Log.i("soundId", soundId.toString() + "")
        // 设置加载完成监听
        soundPool?.setOnLoadCompleteListener { soundPool, sampleId, status ->
            if (status == 0 && sampleId == soundId) { // 加载成功
                soundPool.play(sampleId, 1.0f, 1.0f, 1, 0, 1.0f) // 播放音频
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 释放 SoundPool
        soundPool?.release()
        soundPool = null
    }
}